package com.lexue.articlesync.adapter.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lexue.articlesync.adapter.AbstractPlatformAdapter;
import com.lexue.articlesync.entity.Article;
import com.lexue.articlesync.entity.Video;
import com.lexue.articlesync.entity.PlatformAuth;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

/**
 * 微信公众号平台适配器
 */
@Slf4j
@Component
public class WechatAdapter extends AbstractPlatformAdapter {
    
    private static final String PLATFORM_CODE = "wechat";
    private static final String PLATFORM_NAME = "微信公众号";
    
    // 微信公众号API端点
    private static final String API_BASE_URL = "https://api.weixin.qq.com";
    private static final String TOKEN_URL = API_BASE_URL + "/cgi-bin/token";
    private static final String MEDIA_UPLOAD_URL = API_BASE_URL + "/cgi-bin/media/upload";
    private static final String NEWS_UPLOAD_URL = API_BASE_URL + "/cgi-bin/media/uploadnews";
    private static final String SEND_ALL_URL = API_BASE_URL + "/cgi-bin/message/mass/sendall";
    
    @Override
    public String getPlatformCode() {
        return PLATFORM_CODE;
    }
    
    @Override
    public String getPlatformName() {
        return PLATFORM_NAME;
    }
    
    @Override
    public String[] getSupportedContentTypes() {
        return new String[]{"article"}; // 微信公众号主要支持文章
    }
    
    @Override
    public boolean validateAuth(PlatformAuth auth) {
        if (!super.validateAuth(auth)) {
            return false;
        }
        
        try {
            // 获取access_token来验证认证
            String accessToken = getAccessToken(auth);
            return accessToken != null && !accessToken.isEmpty();
        } catch (Exception e) {
            log.error("验证微信公众号认证失败", e);
            return false;
        }
    }
    
    /**
     * 获取微信公众号access_token
     */
    private String getAccessToken(PlatformAuth auth) throws Exception {
        // 从extraAuthInfo中获取appid和secret
        JSONObject authInfo = JSON.parseObject(auth.getExtraAuthInfo());
        String appId = authInfo.getString("appid");
        String appSecret = authInfo.getString("secret");
        
        String tokenUrl = TOKEN_URL + "?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        
        Request request = createRequestBuilder()
                .url(tokenUrl)
                .build();
        
        try (Response response = executeRequest(request)) {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                JSONObject jsonResponse = JSON.parseObject(responseBody);
                
                if (!jsonResponse.containsKey("errcode")) {
                    return jsonResponse.getString("access_token");
                }
            }
        }
        
        return null;
    }
    
    @Override
    public PublishResult publishArticle(Article article, PlatformAuth auth, PublishOptions options) {
        validateRequired(article.getTitle(), "文章标题");
        validateRequired(article.getContent(), "文章内容");
        
        try {
            String accessToken = getAccessToken(auth);
            if (accessToken == null) {
                return buildFailureResult("获取微信公众号access_token失败");
            }
            
            // 构建图文消息
            JSONObject newsItem = new JSONObject();
            newsItem.put("title", limitLength(options.getTitle() != null ? options.getTitle() : article.getTitle(), 100));
            newsItem.put("content", options.getContent() != null ? options.getContent() : article.getHtmlContent());
            newsItem.put("author", ""); // 作者
            newsItem.put("digest", article.getSummary() != null ? limitLength(article.getSummary(), 120) : "");
            newsItem.put("show_cover_pic", 1);
            
            // 处理封面图片
            if (options.getCoverImage() != null) {
                // 需要先上传图片到微信服务器
                String mediaId = uploadMedia(options.getCoverImage(), "image", accessToken);
                if (mediaId != null) {
                    newsItem.put("thumb_media_id", mediaId);
                }
            }
            
            JSONObject newsData = new JSONObject();
            newsData.put("articles", new JSONObject[]{newsItem});
            
            // 上传图文消息
            String uploadUrl = NEWS_UPLOAD_URL + "?access_token=" + accessToken;
            
            RequestBody body = RequestBody.create(
                    newsData.toJSONString(),
                    MediaType.parse("application/json; charset=utf-8")
            );
            
            Request request = createRequestBuilder()
                    .url(uploadUrl)
                    .post(body)
                    .build();
            
            try (Response response = executeRequest(request)) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    
                    if (!jsonResponse.containsKey("errcode") || jsonResponse.getIntValue("errcode") == 0) {
                        String mediaId = jsonResponse.getString("media_id");
                        
                        // 发送图文消息（群发）
                        if (options.isAutoPublish()) {
                            boolean sent = sendMassMessage(mediaId, accessToken);
                            if (sent) {
                                log.info("微信公众号文章发布成功: {}", mediaId);
                                return buildSuccessResult(mediaId, "");
                            } else {
                                return buildFailureResult("微信公众号文章上传成功但群发失败");
                            }
                        } else {
                            log.info("微信公众号文章上传成功（未群发）: {}", mediaId);
                            return buildSuccessResult(mediaId, "");
                        }
                    } else {
                        String errorMsg = jsonResponse.getString("errmsg");
                        return buildFailureResult("微信公众号发布失败: " + errorMsg);
                    }
                } else {
                    return buildFailureResult(handleErrorResponse(response));
                }
            }
            
        } catch (Exception e) {
            log.error("微信公众号文章发布异常", e);
            return buildFailureResult("微信公众号发布异常: " + e.getMessage());
        }
    }
    
    @Override
    public PublishResult publishVideo(Video video, PlatformAuth auth, PublishOptions options) {
        // 微信公众号不直接支持视频发布，可以发布视频链接或转为图文
        log.warn("微信公众号不支持直接视频发布功能");
        return buildFailureResult("微信公众号不支持直接视频发布功能");
    }
    
    /**
     * 上传媒体文件到微信服务器
     */
    private String uploadMedia(String filePath, String type, String accessToken) {
        try {
            String uploadUrl = MEDIA_UPLOAD_URL + "?access_token=" + accessToken + "&type=" + type;
            
            // 这里简化处理，实际应用中需要上传真实文件
            RequestBody fileBody = RequestBody.create(new byte[0], MediaType.parse("image/jpeg"));
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("media", "cover.jpg", fileBody)
                    .build();
            
            Request request = new Request.Builder()
                    .url(uploadUrl)
                    .post(requestBody)
                    .build();
            
            try (Response response = executeRequest(request)) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    
                    if (!jsonResponse.containsKey("errcode") || jsonResponse.getIntValue("errcode") == 0) {
                        return jsonResponse.getString("media_id");
                    }
                }
            }
        } catch (Exception e) {
            log.error("上传微信媒体文件失败", e);
        }
        
        return null;
    }
    
    /**
     * 群发图文消息
     */
    private boolean sendMassMessage(String mediaId, String accessToken) {
        try {
            String sendUrl = SEND_ALL_URL + "?access_token=" + accessToken;
            
            JSONObject sendData = new JSONObject();
            JSONObject filter = new JSONObject();
            filter.put("is_to_all", true); // 发送给所有用户
            sendData.put("filter", filter);
            
            JSONObject mpnews = new JSONObject();
            mpnews.put("media_id", mediaId);
            sendData.put("mpnews", mpnews);
            sendData.put("msgtype", "mpnews");
            
            RequestBody body = RequestBody.create(
                    sendData.toJSONString(),
                    MediaType.parse("application/json; charset=utf-8")
            );
            
            Request request = createRequestBuilder()
                    .url(sendUrl)
                    .post(body)
                    .build();
            
            try (Response response = executeRequest(request)) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    
                    return !jsonResponse.containsKey("errcode") || jsonResponse.getIntValue("errcode") == 0;
                }
            }
        } catch (Exception e) {
            log.error("群发微信消息失败", e);
        }
        
        return false;
    }
}